import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'future-pane.dart';

abstract class LoadingListPage<B> extends StatefulWidget {
  LoadingListPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _LoadingPageState createState() => _LoadingPageState();

  Future<List<B>> loadData(bool isfresh);

  Widget buildListCell(BuildContext context, B b);
}

class _LoadingPageState extends State<LoadingListPage> {

  bool loading = false;
  List _listData = new List();
  ScrollController _scrollController = ScrollController(); //listview的控制器
  ShowType _showType = ShowType.loading;
  bool _isLoadEnd = false;

  @override
  void initState() {
    super.initState();
    Future<List> _futureData = widget.loadData(true);
    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        print('滑动到了最底部');
        _moreData();
      }
    });
    _futureData.then((datas) {
      _mergeData(datas);
      _showType = ShowType.data;
    });
    _futureData.catchError((onError) {
      setState(() {
        _showType = ShowType.error;
        print("error!!");
    });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text(widget.title),
        ),
        body: new RefreshIndicator(
          onRefresh: _pullToRefresh,
          child: new FuturePane(
            isShowInit: _showType,
            child: _buildList()
          )
      ),
    );
  }

  Widget _buildList() {
    return new ListView.builder(
        itemCount: _listData.length + (_isLoadEnd ? 0 : 1),
        controller: _scrollController,
        itemBuilder: (BuildContext context, int index) {
          if (index < _listData.length) {
            var data = _listData[index];
            return _row(data);
          }
          return _loadingRow();
        },
    );
  }

  Widget _row(dynamic data) {
    Widget cell = widget.buildListCell(context, data);
    return new Container(
      decoration: new BoxDecoration(
          border: new Border(
              bottom: new BorderSide(color: Colors.grey.shade300)
          )
      ),
      child: cell,
    );
  }

  void _mergeData(List datas) {
    if (datas.length < 10) {
      _isLoadEnd = true;
    }
    if (_listData.length < 1) {
      setState(() {
        _listData.addAll(datas);
        print("setState");
      });
      return;
    }
    List list = new List();
    List isSame = new List();
    for (var t in _listData) {
      bool isHave = false;
      for (var b in datas) {
        if (t == b) {
          list.add(b);
          isSame.add(b);
          isHave = true;
          break;
        }
      }
      if (!isHave) {
        list.add(t);
      }
    }
    for (var b in datas) {
      bool isHave = false;
      for (var t in isSame) {
        if (t == b) {
          isHave = true;
          break;
        }
      }
      if (!isHave) {
        list.add(b);
      }
    }
//    _listData.addAll(datas);
    setState(() {
      _listData = list;
      print("setState");
    });
  }

  Future _pullToRefresh() async {
    if (loading) return null;
    loading = true;
    print("start load data!!!!!!!!!!!!!!");
    Future<List> _futureData =  widget.loadData(true);
    _futureData.then((datas) {
      print("merge data");
      _mergeData(datas);
    });
    _futureData.whenComplete((){
      loading = false;
    });
    return _futureData;
  }

  Future _moreData() async {
    if (loading) return null;
    loading = true;
    print("start load data!!!!!!!!!!!!!!");
    Future<List> _futureData =  widget.loadData(false);
    _futureData.then((datas) {
      print("merge data");
      _mergeData(datas);
    });
    _futureData.whenComplete((){
      loading = false;
    });

    return _futureData;
  }

  /**
   * 加载更多时显示的组件,给用户提示
   */
  Widget _loadingRow() {
    return SizedBox(
      height: 50.0,
      child: Center(
        child: Padding(
          padding: EdgeInsets.all(10.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text(
                '加载中...',
                style: TextStyle(fontSize: 16.0),
              ),
              CircularProgressIndicator(
                strokeWidth: 1.0,
              )
            ],
          ),
        ),
      ),
    );
  }

}

